package qf.sail.dao.impl;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import qf.sail.dao.AccountDao;
import qf.sail.entity.Account;
import qf.sail.util.DBUtil;

import java.math.BigInteger;
import java.sql.SQLException;

public class AccountDaoImpl implements AccountDao {

    private QueryRunner queryRunner = new QueryRunner(DBUtil.getDataSource());

    @Override
    public Account findAccountById(Long id) {
        String sql = "SELECT * FROM Account WHERE id=?";
        Object[] params = {id};

        Account account = null;
        try {
            account = queryRunner.query(sql, DBUtil.getBeanHandler(Account.class),params);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return account;
    }

    @Override
    public Account findAccountByPhone(String phone) {
        String sql = "SELECT * FROM Account WHERE phone=?";
        Object[] params = {phone};

        Account account = null;
        try {
            account = queryRunner.query(sql, DBUtil.getBeanHandler(Account.class),params);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return account;
    }

    @Override
    public int addAccount(Account account) {
        String sql = "INSERT INTO account (phone,`password`,sex,birth,head_pic) VALUES (?,?,?,?,?)";
        Object[] params = {account.getPhone(),account.getPassword(),account.getSex(),account.getBirth(),account.getHead_pic()};
        try {
            int update = queryRunner.update(sql,params);
            return update;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            return 0;
        }
    }


    public long addAccountTest(Account account) {
        String sql = "INSERT INTO account (phone,`password`,sex,birth,head_pic) VALUES (?,?,?,?,?)";
        Object[] params = {account.getPhone(),account.getPassword(),account.getSex(),account.getBirth(),account.getHead_pic()};
        try {
            BigInteger id = queryRunner.insert(sql, new ScalarHandler<BigInteger>(), params);
            return id.longValue();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            return 0;
        }
    }



}
